<?php

namespace Home\Controller;

class CartController extends CommonController {

    public function addToCart() {//添加到购物车
        $id = I("post.id", 0, 'int');
        $num = I("post.num", 1, 'int');
        $carts = json_decode(cookie("cart"), true);
        $is_has = 0;
        if (empty($carts)) {
            $carts = array(0 => array("id" => $id, "num" => $num));
        } else {
            foreach ($carts as $k => $v) {
                if ($v['id'] == $id) {
                    $is_has++;
                    $carts[$k]['num'] = $v['num'] + $num;
                    break;
                }
            }
            if ($is_has == 0) {
                array_push($carts, array("id" => $id, "num" => $num));
            }
        }
        cookie("cart", json_encode($carts));

//        echo json_encode(array("sid" => $goods['sid'], "id" => $id, "name" => $shop['name']));
    }

    public function addCut() {//加减
        $id = I("post.id", 0, 'int');
        $num = I("post.num", 0, 'int');

        $carts = json_decode(cookie("cart"), true);
        if ($carts) {
            foreach ($carts as $k => $v) {
                if ($num == 0) {
                    if ($v['id'] == $id) {
                        unset($carts[$k]);
                    }
                } else {
                    if ($v['id'] == $id) {
                        $carts[$k]['num'] = $num;
                        break;
                    }
                }
            }
        }
        if ($carts) {
            cookie("cart", json_encode($carts));
        } else {
            cookie("cart", null);
        }
    }

    public function emptyCart() {
        cookie("cart", null);
    }

    public function confirm() {
        session('returnUrl', __SELF__);
        $id = I("post.id") ? I("post.id") : session("cart_id");
        $num = I("post.num") ? I("post.num") : session("cart_num");
        if ($id) {
            session("cart_id", $id);
            session("cart_num", $num);
        } else {
            $this->error("购物车为空！");
        }
        if (session("userid") == '') {
            $this->redirect("Login/index");
        }
        $carts = array();
        foreach ($id as $k => $v) {
            if ($v > 0 && $num[$k] > 0) {
                $carts[$k]['id'] = $v;
                $carts[$k]['num'] = $num[$k];
            }
        }
        foreach ($carts as $k => $v) {
            $info = M("goods")->field("name,price,discount,sid,is_bag")->where("id = " . $v['id'] . "")->find();
            $sids[] = $info['sid'];
            $carts[$k]['name'] = $info['name'];
            $carts[$k]['price'] = $info['price'];
            $carts[$k]['discount'] = $info['discount'];
            $carts[$k]['sid'] = $info['sid'];
            $carts[$k]['is_bag'] = $info['is_bag'];
            $carts[$k]['num'] = $v['num'];
        }

        if ($sids) {
            $sids = array_unique($sids);
            $cartsArr = array();
            $total_price = 0;
            $sendprice = 0; //配送费
            $sendtimes = 0;

            foreach ($sids as $k => $v) {

                $shop = M("shop")->field("logo,name,startprice,sendprice,sendtimes,sales_cut,sales_full")->where("id = " . $v . "")->find();
                $cartsArr[$k]['id'] = $v;
                $cartsArr[$k]['name'] = $shop['name'];
                $cartsArr[$k]['sales_cut'] = $shop['sales_cut'];
                $cartsArr[$k]['sales_full'] = $shop['sales_full'];
                $shop_price = 0;
                $i = 0;
                $bags = 0; //打包费
                foreach ($carts as $k2 => $v2) {
                    if ($v == $v2['sid']) {
                        $cartsArr[$k]['sub'][] = $v2;
                        $shop_price += $v2['price'] * $v2['num'];
                        $cartsArr[$k]['sub'][$i]['discount'] = sprintf("%.1f", $v2['discount']);
                        $cartsArr[$k]['sub'][$i]['price_total'] = sprintf("%.1f", ($v2['price'] - $v2['discount']) * $v2['num']);
                        if ($v2['is_bag'] == 1) {
                            $bags +=1 * $v2['num'];
                        }
                        $i++;
                    }
                }
//                if ($shop['sendtimes']) {
//                    $sendtimes += $shop['sendtimes']; //团购送餐时间\
//                }
                $sendprice += $shop['sendprice'];
                $cartsArr[$k]['bags'] = $bags;
                $cartsArr[$k]['shop_price'] = sprintf("%.1f", $shop_price);
                $cartsArr[$k]['sendprice'] = sprintf("%.1f", $shop['sendprice']);
                $cartsArr[$k]['sendtimes'] = $shop['sendtimes'];
                $total_price += $cartsArr[$k]['shop_price'];
                if ($total_price >= $shop['sales_full'] && $shop['sales_cut'] > 0) {
                    $total_price = $total_price - $shop['sales_cut'];
                }
            }
        }
//        print_r($cartsArr);
        $addrs = M("addr")->where("uid = " . session("userid") . "")->order("id DESC")->select();
        $this->assign('total_price', sprintf("%.1f", $total_price + $sendprice + $bags));
        $this->assign('cartsArr', $cartsArr);
        $this->assign('cartsNum', count($cartsArr));
        $this->assign('addrs', $addrs);
        $this->assign('sendprice', sprintf("%.1f", $sendprice));
        $this->assign('num', $num);
        $this->assign('id', $id);
        $this->assign('sendtimes', $sendtimes);
        $this->assign("times", getTimes()); //送出时间
        $this->assign("shop", $shop);
        $config = getTableConfig();
        if ($config['cart_type'] == 1) {
            $modal = 'confirm_more';
        } else {
            $modal = 'confirm_single';
        }
        $this->display("Cart:" . $modal . "");
    }

    public function submit() {
        $three = json_decode(getTableField("shortMessage", "three"), true);
        $sendtime = I("post.sendtime");
        if ($sendtime > 0) {
            $hour = intval($sendtime / 60);
            $minites = intval($sendtime % 60);
            if (strlen($minites) == 1) {
                $minites = "0" . $minites;
            }
            $remark_send = "&nbsp;" . $hour . ":" . $minites . "送出";
        }
        $addr_id = I("post.addr_id", 0, 'int');
        $addr = M("addr")->field("addr,truename,phone,phone2")->where("id = " . $addr_id . " AND uid = " . session("userid") . "")->find();
        foreach ($addr as $k => $v) {
            $data[$k] = $v;
        }
        if (empty($addr)) {
            $this->error("请选择地址！");
        }
        $ids = I("post.id");
        $nums = I("post.num");
        if (!$ids) {
            $this->error("购物车为空！");
        }
        $idsImplode = implode(",", $ids);
        $goods_cart = M("goods")->field("id,sid,name,price,discount,is_bag")->where("id in (" . $idsImplode . ")")->select();
        $sidArr = array(); //店铺id
        $carts = json_decode(cookie("cart"), true);
        foreach ($goods_cart as $v) {
            $sidArr[] = $v['sid'];
            foreach ($carts as $k2 => $v2) {
                if ($v2['id'] == $v['id']) {
                    unset($carts[$k2]);
                }
            }
        }
        $i = 0;
        foreach ($carts as $v) {
            $cartsNew[$i] = $v;
            $i++;
        }

        $sidArr = array_unique($sidArr);
        $goodsArr = array(); //商品数组


        foreach ($sidArr as $k => $v) {
            $bags = 0; //打包费     
            $totalMoney = 0;
            $discount = 0;
            foreach ($goods_cart as $v2) {
                if ($v2['sid'] == $v) {
                    $gidKey = array_search($v2['id'], $ids);
                    $totalMoney += $v2['price'] * $nums[$gidKey];
                    $discount += $v2['discount'] * $nums[$gidKey];
                    if ($v2['is_bag'] == 1) {
                        $bags += 1 * $nums[$gidKey];
                    }
                }
            }

            $shop = M("shop")->field("name,sales_cut,sales_full,business_time,weeks,is_busy,sendprice")->where("id = " . $v . "")->find();
//            $shopState = getShopState($shop['business_time'], $shop['weeks'], $shop['is_busy']);
//            if ($shopState != '') {//判断店铺状态
//                $this->error($shop['name'] . $shopState);
//            }
            $data['totalMoney'] = $totalMoney + $shop['sendprice'] + $bags;
            if ($totalMoney > $shop['sales_full']) {//若订单额大于满价
                $data['realMoney'] = $data['totalMoney'] - $shop['sales_cut'] - $discount;
            } else {
                $data['realMoney'] = $data['totalMoney'] - $discount;
            }
            $data['sendprice'] = $shop['sendprice'];
            $data['ordernum'] = getOrdernum();
            $data['addtime'] = time();
            $data['remark'] = I("post.remark_" . $v . "") . $remark_send;
            $data['sid'] = $v;
            $data['bags'] = $bags;
            $data['uid'] = session("userid");
            $goodsArr['pid'] = M("order")->add($data); //订单id
            //添加商品到订单
            foreach ($goods_cart as $v2) {
                if ($v2['sid'] == $v) {
                    $gidKey = array_search($v2['id'], $ids);
                    $goodsArr['gprice'] = $v2['price'] - $v2['discount'];
                    $goodsArr['gname'] = $v2['name'];
                    $goodsArr['gid'] = $v2['id'];
                    $goodsArr['gnum'] = $nums[$gidKey];
                    $goodsArr['is_bag'] = $v2['is_bag'];
                    M("order_goods")->add($goodsArr);
                }
            }
            sendEmailOrder($goodsArr['pid']);
            if ($three['send_method'] == 0) {
                sendMobileOrder($goodsArr['pid']);
            }
        }
        cookie("cart", json_encode($cartsNew));
        $this->redirect("Order/success", array("id" => $goodsArr['pid']));
    }

}

?>
